/**
 *
 */
$(function(){
    $(document).keyup(function (e) {
        if(e.which==13){
            $('#selectBtnEnter').click();
        }
    })
});
var path = '../';
var pageListUrl = path + 'postion/customerTotalList';
var pageUrl = path + 'postion/';

//添加弹窗
var addPanel = null;
var addPanelPicture = null;
// ---------------交互代码begin-----------------
//本页面业务逻辑
var postion = {
    checkLogic: function (dataObj) {
        var result = "";
        var isSubmit = true;
        //TODO 逻辑校验，去掉不必要的:
        //检查表单是否存在错误
        $.each(dataObj, function (key) {
            if (key.indexOf('Err') != -1 && dataObj[key].length > 0) {
                return false;
            }
        });
        return isSubmit;
    },
    checkFileType: function () {
        var fileName = $("#file")[0].files[0].name;
        var fileType = fileName.substr(fileName.lastIndexOf(".") + 1, fileName.length);
        if (fileType.toUpperCase() != 'XLSX' && fileType.toUpperCase() != 'XLS') {
            importVue.fileErr = "请选择*.xlsx或者*.xls格式的Excel文件";
            return false;
        }
        return true;
    }
};
//本页面业务逻辑
var advInfo={
    checkLogic:function(dataObj,err,fg){
        advInfo.clear(err);
        console.log(dataObj)
        var result="";
        var isSubmit=true;
        //TODO 逻辑校验，去掉不必要的:
        result=customUtils.checkLen(dataObj.postionCode,1,32,'位置编号');
        if(result.length!=0){
            err.positionCodeErr=result;
            isSubmit=false;
        }
        $.ajax({
            url : pageUrl + "checkPositionCode",
            type : "POST",
            dataType: "json",
            data : {postionCode:dataObj.postionCode},
            cache:false ,
            async: false
        }).done(function(res) {
            if(res.result=='0'){
                err.positionCodeErr='位置编号不存在';
                isSubmit=false;
            }
        })
        var topImg = $("#topImg")[0].files[0];
        //文件空校验
        if(!topImg){
            err.topImgErr = "请上传广告资源";
            isSubmit = false;
        }

        //文件格式校验
        var imgType = ["jpg","png","gif","jpeg","bmp"];
        var videoType = ["mp4","avi","mov","asf","wmv","rm"];
        var musicType = ["mp3"];
        // if(topImg && bottomImg && middleVideo){
        if(topImg){
            var type = topImg.name.substr(topImg.name.lastIndexOf(".") + 1,topImg.name.length).toLowerCase();
            if($.inArray(type,imgType) == '-1'){
                err.topImgErr = "请上传" + imgType.toString() + "格式的图片";
                isSubmit = false;
            }
        }
        console.log(err)
        //检查表单是否存在错误
        $.each(err, function(key) {
            if(key.indexOf('Err')!=-1 && err[key].length>0){
                return false;
            }
        });
        return isSubmit;
    },
    clear:function(obj){
        $.each(obj,function (key) {
            if($.isArray(obj[key])){
                obj[key] = [];
            }else{
                obj[key] = "";
            }
        });
    }
};
//绑定列表List---begin----所有的操作都围绕列表展开，新增、更新其他比较独立 
var dataList = new Vue({
    el: "#postionList",
    data: {
        pageInfo: {},
        pageInfo1: {},
        pageInfo2: {},
        //TODO 自定义条件查询---begin--------
        condition: {
            page: 1,
            rows: customUtils.pageSize,

            items: [],
            all: false,
            key: "",
            equipmentCode:"",
            param1:"",
            param2:"",
            province: "",
            city: "",
            area: "",
            statusOk: "",
            statusNo: "",
            Percentage: "",


            provinces: [],
            citys: [],
            areas: [],


            id: "",
            postionCode: "",
            shopCode: "",
            companyName: "",
            shopName: "",
            shopContacts: "",
            shopPhone: "",
            empno: "",

            address: "",
            createdBy: "",
            createdDate: "",
            updatedBy: "",
            updatedDate: "",
            installPhoto: "",
            installDate: "",
            flowRate:"",
            status: "",
            overDate:"",
            startDate:""
        },
        //自定义条件查询---end--------
        selectIds: [],//多选
        showSuccess: false,//false不显示成功提示
        selectedIdx: -1,//保存操作行的索引
        isSearch: false,//init:页面初始化；search:点击查询；paging:点击翻页；changePageSize:改变页面显示条数
        selectedPageSize: customUtils.pageSize//修改页面数据显示条数
    },
    mounted: function () {
        //初始化页面数据
        //this.getAreaData();
        //this.getList('init');
        //this.getStatus();
    },
    // 在 `methods` 对象中定义方法,如果操作中函数的逻辑比较复杂，必须封装到dictType对象
    methods: {
        changeTime: function (elem) {
            addOrUpdate[elem.split('-')[0]] = $("#" + elem).val();
        },
        selectChkBtn: function (e) {//用于多选事件
            this.selectIds.push($(e.target).val());
        },
        changeTime:function(elem){
            dataList.$data.condition[elem.split('-')[0]] = $("#"+elem).val();
            console.log(dataList.$data.condition);
        },
        getAreaData: function () {
            this.$http.get("../appInfo/queryAreaTree").then(function (response) {
                console.log(response)
                dataList.$data.condition.provinces = response.body;
                console.log(dataList.$data)
            }, function (res) {

            });
        },
        setCitys: function () {
            dataList.$data.condition.citys = dataList.$data.condition.province.citys;
            dataList.$data.condition.city = "";
            dataList.$data.condition.area = "";
        },
        setAreas: function () {
            dataList.$data.condition.areas = dataList.$data.condition.city.areas;
            dataList.$data.condition.area = "";
        },
        exportCustomerFlowTotal: function () {
            var self=this;
            var equipmentCode = self.condition["equipmentCode"];
            if(equipmentCode.length>0){
                var startDate = self.condition["startDate"];
                var overDate = self.condition["overDate"];
                var param2 = "customer_flow_total";
                location.href=pageUrl+"exportCustomerFlowTotal?equipmentCode="+equipmentCode+"&startDate="+startDate+"&startDate="+startDate+"&overDate="+overDate+"&param2="+param2;
            }else{
                alert("请输入设备编号");
                return;
            }
        },

        //搜索、分页列表
        getList: function (eventSrc) {
            var self = this;
            //改变页面显示条数
            if (eventSrc == "changePageSize") {
                if (this.pageInfo.pageSize != this.selectedPageSize) {
                    this.pageInfo.pageSize = this.selectedPageSize;
                    $('#pagination').jqPaginator('destroy');                    eventSrc = 'init';//重新绘制控件
                } else {
                    return;
                }
            }
            var param = {"page": 1, "rows": customUtils.pageSize};

            //初始化时无当前页数，后台有默认第1页，每页10条
            if (this.pageInfo != undefined && this.pageInfo.pageNum != undefined) {
                self.condition["page"] = this.pageInfo.pageNum;
                self.condition["rows"] = this.pageInfo.pageSize;
            }
            param["page"] = self.condition["page"];
            param["rows"] = self.condition["rows"];
            param["param3"] = self.condition["startDate"];
            param["param4"] = self.condition["overDate"];
            param["param1"] = "postion";
            param["param2"] = "customer_flow_total";
            param["equipmentCode"] = self.condition["equipmentCode"];
            //param["startDate"] = self.condition["startDate"];
            /*param["province"] = self.condition["province"] == '' ? "" : self.condition["province"].code;
            param["city"] = self.condition["city"] == '' ? "" : self.condition["city"].code;
            param["area"] = self.condition["area"] == '' ? "" : self.condition["area"].code;
            param["status"] = self.condition["status"];*/
            this.condition.items = [];
            console.log(param)

            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self, pageListUrl, param, function (response, isSuccess) {
                if (isSuccess == false) {
                    dataList.pageInfo.pages = 0;
                    customUtils.noData('无数据', 0);
                    return;
                }
                dataList.pageInfo = response.body.pagination;
                dataList.pageInfo1 = response.body.list1;
                dataList.pageInfo2 = response.body.sumList;
                customUtils.noData('无数据', dataList.pageInfo.pages);
                //页面初始化、搜索时，才需要执行分页控件
                if (eventSrc == 'init' || eventSrc == 'search') {
                    customUtils.paging('#pagination', dataList.pageInfo.pages, customUtils.showPage, function (num) {
                        //当前页码pageNum与将要翻页的页码num不相等才执行，否则为同一页
                        if (dataList.pageInfo.pageNum != num) {
                            dataList.pageInfo.pageNum = num;
                            dataList.getList('paging');
                        }
                    });
                }
            }, function (response) {
                console.log(response);
                dataList.pageInfo.pages = 0;
                customUtils.noData('无数据', 0);
            });

        },
        getStatus: function () {
            var self = this;
            var param = {};
            param["statusOk"] = self.condition["statusOk"];
            param["statusNo"] = self.condition["statusNo"];
            param["Percentage"] = self.condition["Percentage"];
            console.log(param)
            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self, pageUrl + "getStatus", param, function (response, isSuccess) {

                dataList.$data.condition.statusNo = response.body.statusNo;
                dataList.$data.condition.statusOk = response.body.statusOk;
                dataList.$data.condition.Percentage = Math.round((response.body.statusOk / (response.body.statusNo + response.body.statusOk)) * 10000) / 100;
            }, function (response) {
                console.log(response)
            });
        },
        getStatusByCondition: function () {
            var self = this;
            var param = {};
            param["key"] = self.condition["key"];
            param["province"] = self.condition["province"] == '' ? "" : self.condition["province"].code;
            param["city"] = self.condition["city"] == '' ? "" : self.condition["city"].code;
            param["area"] = self.condition["area"] == '' ? "" : self.condition["area"].code;
            param["status"] = self.condition["status"];
            console.log(param)
            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self, pageUrl + "getStatusByCondition", param, function (response, isSuccess) {

                dataList.$data.condition.statusNo = response.body.statusNo;
                dataList.$data.condition.statusOk = response.body.statusOk;
                dataList.$data.condition.Percentage = Math.round((response.body.statusOk / (response.body.statusNo + response.body.statusOk)) * 10000) / 100;
            }, function (response) {
                console.log(response)
            });
        },
        importPostion: function () {
            var obj3 = document.getElementById('file');
            obj3.outerHTML = obj3.outerHTML;
            importVue.fileErr = "";
            importPanel = layer.open({
                type: 1,
                title: "导入位置信息",
                area: ['600px', '70%'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#importPanel')
            });
        },
//打开添加对话框
        addOrUpdatePanelPicture:function(flag){
            var obj1 = document.getElementById('topImg') ;
            obj1.outerHTML=obj1.outerHTML;
            advInfo.clear(addOrUpdate.$data.err);
            advInfo.clear(addOrUpdate.$data.field);

            console.log(addOrUpdate.$data.field)
            if(flag != 'update'){
                addOrUpdate.$data.id="";
                addOrUpdate.$data.field.advType = '2';
                $(".t11").hide();
            }else{
                $(".t12").show();
            }
            //清除表单数据，否则会有前一条修改数据的内容
            // $.each(addOrUpdate.$data, function(key) {
            // addOrUpdate[key]="";
            // });
            var tmpTitle =  flag=="add"?"添加":"修改";
            addOrUpdate.typeChange()
            addPanelPicture = layer.open({
                type : 1,
                title :tmpTitle+"安装广告机图片上传",
                area : [ '650px', '80%' ],
                shadeClose : false, // 点击遮罩关闭
                content : $('#addPanelPicture')
            });
        },
        //更新状态
        updateStatus: function (status) {
            var size = dataList.condition.items.length;
            if (size <= 0) {
                return;
            }
            var str = status == 1 ? "有效" : "无效";
            var msg = "您确定要将" + size + " 条位置信息置为<" + str + ">状态";
            var self = this;
            layer.confirm(msg, function (index) {
                var param = {};
                param["items"] = JSON.stringify(dataList.condition.items);
                param["status"] = status;
                customUtils.post(self, pageUrl + "/updateStatus", param, function (response, isSuccess) {

                    dataList.getList('no');
                }, function (response) {
                    customUtils.showRequestTips(response, 3000)
                });
                layer.close(index);
                return true;
            });
            return false;
        },
        //初始化更新，更新对话框
        updateInit: function (index) {
            //先显示窗口，才有加载效果
            this.addOrUpdatePanel("update");
            var record = this.pageInfo.list[index];
            this.selectedIdx = index;
            var url = pageUrl + 'id/' + record.id;
            var self = this;
            customUtils.get(self.$http, url, function (response, isSuccess) {
                if (isSuccess == false) {
                    return;
                }
                //回显表单数据
                $.each(response.body, function (key) {
                    if (addOrUpdate[key] !== undefined && response.body[key]) {
                        addOrUpdate[key] = response.body[key];
                    }
                });
            }, function (response) {
                console.log(response);
            });
        },
        //全选--取消全选方法
        checkAll: function () {
            console.log(this.condition);
            if (this.condition.all) {
                this.condition.all = false;
                $("tbody").find("input[type='checkbox'][name='id']").each(function (i, val) {
                    dataList.condition.items = [];
                });
            } else {
                this.condition.all = true;
                $("tbody").find("input[type='checkbox'][name='id']").each(function (i, val) {
                    dataList.condition.items[i] = val.value;
                });
            }
        },


        //打开添加对话框
        addOrUpdatePanel: function (flag) {
            //清除表单数据，否则会有前一条修改数据的内容
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
            var tmpTitle = flag == "add" ? "添加" : "修改";
            addPanel = layer.open({
                type: 1,
                title: tmpTitle + "位置管理",
                area: ['570px', 'auto'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#addPanel')
            });
        }
    },
    filters: {
        // 时间格式化
        timeStamps (StatusMinute) {
            if(StatusMinute==null){
                return StatusMinute = "一天未在线";
            }
            var day = parseInt(StatusMinute / 60 / 60 / 24)
            var hour = parseInt(StatusMinute / 60 / 60 % 24)
            var min = parseInt(StatusMinute / 60 % 60)
            var second = parseInt(StatusMinute / 60 % 60 % 60)
            StatusMinute = ""
            if (day > 0) {
                StatusMinute = day + "天"
            }
            if (hour > 0 && day < 1) {
                StatusMinute += hour + "小时"
            }
            if (min > 0 && day < 1) {
                StatusMinute += parseFloat(min) + "分钟"
            }
            if (second > 0 && day < 1) {
                StatusMinute += parseFloat(second) + "秒"
            }
            if(min == 0) {
                StatusMinute = "一天未在线"
            }
            return StatusMinute
        }
    }
});
//绑定列表List---end----

//新增或更新---------begin-------
var addOrUpdate = new Vue({
    el: "#addPanelPicture",
    data: {
        postionCode: "",
        shopCode: "",
        companyName: "",
        shopName: "",
        shopContacts: "",
        shopPhone: "",
        empno: "",
        address: "",
        updatedBy: "",
        updatedDate: "",
        id: "",
        //以下是错误信息
        postionCodeErr: "",
        shopCodeErr: "",
        companyNameErr: "",
        shopNameErr: "",
        shopContactsErr: "",
        shopPhoneErr: "",
        empnoErr: "",
        addressErr: "",
        updatedByErr: "",
        updatedDateErr: "",
        showSuccess: true,//显示成功提示
        field:{
            id:"",
            advCode:"",
            positionCode:"",
            advType:"3",
            maxAge:"",
            minAge:"",
            sex:"2",
            topImg:"",
            bottomImg:"",
            middleVideo:"",
            price:""
        },
        //错误信息
        err:{
            positionCodeErr:"",
            advCodeErr:"",
            advNameErr:"",
            maxAgeErr:"",
            minAgeErr:"",
            sexErr:"",
            advPathErr:"",
            topImgErr:"",
            bottomImgErr:"",
            middleVideoErr:"",
            advTypeErr:"",
            priceErr:""
        }
    },
    //当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch: {},
    methods: {
        changeTime: function (elem) {
            addOrUpdate[elem.split('-')[0]] = $("#" + elem).val();
        },
        save: function () {
            //逻辑校验
            if (!postion.checkLogic(this.$data)) {
                return;
            }
            //没有id的时候表示新增，否则为更新
            var actionUrl = this.id == "" ? 'save' : 'update';
            var self = this;
            customUtils.post(self, pageUrl + actionUrl, self.$data, function (response, isSuccess) {
                if (actionUrl == 'update') {
                    var record = dataList.pageInfo.list[dataList.selectedIdx];
                    //更新成功，刷新列表中对应的数据
                    $.each(record, function (key) {
                        if (addOrUpdate[key] != undefined) {
                            record[key] = addOrUpdate[key];
                        }
                    });
                } else if (isSuccess) {
                    dataList.getList('init');
                }
                if (isSuccess && addPanel) layer.close(addPanel);
            }, function (res) {
                //console.log(response.body);
            });
        },
        typeChange:function () {
            var b = addOrUpdate.$data.field.advType;
            if(b ==6){
                $("#t1").hide();
                $("#t2").show();
                // $("#t_age").show();
                // $("#t_sex").show();
                // $("#tl").html("顶部图片：")
                // $("#ml").html("中部视频：")
                // $("#topImg").prop("multiple",false);
            }else{
                $("#t1").show();
                $("#t2").hide();
            }
            // if(b ==2){

            //     $("#t_age").hide();
            //     $("#t_sex").hide();
            //     $("#tl").html("前景图片：")
            //     $("#ml").html("背景音乐：")
            //     // $("#topImg").prop("multiple",true);
            // }
        },
        savePicture:function(){
            //没有id的时候表示新增，否则为更新
            var actionUrl=this.field.id=="" ? 'save' :'update';
            //逻辑校验
            if(!advInfo.checkLogic(this.$data.field,this.$data.err,actionUrl)){
                return;
            }
            var self=this;
            var formDate = new FormData($("#addPanelPicture")[0]);
            console.log(self.$data)
            customUtils.post(self,pageUrl + "savePicture",formDate,function(response,isSuccess){
                customUtils.showTips(response.body,addOrUpdate.$data.err)
                dataList.getList('init');
                if(isSuccess && addPanelPicture)layer.close(addPanelPicture);
            },function(res){
                //console.log(response.body);
            });
        },
        //清除表单数据
        reset: function () {
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
        },
        resetPicture: function () {
            if(addPanelPicture)layer.close(addPanelPicture);
        }
    }
});

//新增或更新---------end-------

var importVue = new Vue({
    el: "#importPanel",
    data: {
        fileErr: ""
    },
    methods: {
        importB: function () {
            var self = this;
            if (!postion.checkFileType()) {
                return;
            }
            console.log($("#importPanel"))
            console.log($("#importPanel").find("#file")[0].files)
            var formDate = new FormData($("#importPanel")[0]);
            //没选择文件时
            if ($("#importPanel").find("#file")[0].files.length <= 0) {
                $(".errMsg").html("请选择要上传的数据文件");
                return;
            }
            customUtils.post(self, pageUrl + "uploadCustomerFlowTotal", formDate, function (response) {
                console.log(response);
                customUtils.showTips(response.body, null, 2000);
                var html = "";
                if (response.body.errList != 'undefined' && response.body.errList != '' && response.body.errList != null) {
                    response.body.errList.forEach(function (value, index) {
                        html = html + value + "<br>";
                    });
                    $(".errMsg").html(html);
                } else {
                    if (importPanel) layer.close(importPanel);
                    dataList.getList('init');
                }
            }, function (response) {
                customUtils.showRequestTips(response, 3000)
            })
            console.log(formDate);
        }
    }

});

var path = "../";

var lineList = [];
var date = [];
var echartList = [];
var chartToTotal1 = echarts.init(document.getElementById('chartToTotal'));
var chartToTotal2 = echarts.init(document.getElementById('chartToTotalRemoveWeekend'));
var chartToTotal3 = echarts.init(document.getElementById('chartToTotalOfSex'));
var chartToTotal4 = echarts.init(document.getElementById('chartToTotalOfAge'));
var chartToTotalAge1 = echarts.init(document.getElementById('chartToTotalEarlyYouth'));
var chartToTotalAge2 = echarts.init(document.getElementById('chartToTotalYouth'));
var chartToTotalAge3 = echarts.init(document.getElementById('chartToTotalAdult'));
var chartToTotalAge4 = echarts.init(document.getElementById('chartToTotalMeddleAge'));
var chartToTotalAge5 = echarts.init(document.getElementById('chartToTotalOldAge'));
var chartTototalHour = echarts.init(document.getElementById('chartToTotalHour'));

function chartToAll() {
    chartToTotalFunction('1');
    chartToTotalFunction('2');
    chartToTotalOfSexAndAgeFunction('1');
    chartToTotalOfSexAndAgeFunction('2');
    chartToTotalAgeFunction('1');
    chartToTotalAgeFunction('2');
    chartToTotalAgeFunction('3');
    chartToTotalAgeFunction('4');
    chartToTotalAgeFunction('5');
    chartToTotalHourFunction();
}
function chartToTotalFunction(type) {
    if(type=='1'){
        var chartToTotal = chartToTotal1;
        document.getElementById('chartToTotal').style.display='';
    }
    if(type=='2'){
        var chartToTotal = chartToTotal2;
        document.getElementById('chartToTotalRemoveWeekend').style.display='';
    }
    var equipmentCode = $("#keyword").val();
    if (equipmentCode.length==0){
        return;
    }
    var param3 = $("#startDate-d").val();
    var param4 = $("#overDate-d").val();
    $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: path + "postion/chartToTotal",    //请求发送到getTig处
        data: {param1: 'customer_flow_total',
            param2:type,
            param3:param3,
            param4:param4,
            equipmentCode:equipmentCode},
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            //请求成功时执行该函数内容，result即为服务器返回的json对象
            if (result.echartList.length>0) {
                echartList = [];
                date = [];
                color = "#1980ff";
                for (var i = 0; i < result.echartList.length; i++) {
                    if (result.echartList[i].total != undefined) {
                        echartList.push(result.echartList[i].total);
                    }
                }
                for (var i = 0; i < result.echartList.length; i++) {
                    if (result.echartList[i].chineseDate != undefined) {
                        date.push(result.echartList[i].chineseDate);
                    }
                }
                var option=setOptionParamBar(result);
                chartToTotal.setOption(option);
            } else {
                chartToTotal.clear();
                if(type=='1'){
                    document.getElementById('chartToTotal').style.display='none';
                }
                if(type=='2'){
                    document.getElementById('chartToTotalRemoveWeekend').style.display='none';
                }
            }
        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败!");
            chartToTotal.hideLoading();
        }
    });
};

function chartToTotalHourFunction() {
    var chartToTotal = chartTototalHour;
    var equipmentCode = $("#keyword").val();
    document.getElementById('chartToTotalHour').style.display='';
    if (equipmentCode.length==0){
        return;
    }
    var param3 = $("#startDate-d").val();
    var param4 = $("#overDate-d").val();
    $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: path + "postion/chartToFlowTotalHourAvg",    //请求发送到getTig处
        data: {
            param3:param3,
            param4:param4,
            equipmentCode:equipmentCode
        },
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            //请求成功时执行该函数内容，result即为服务器返回的json对象
            if (result.echartList.length>0) {
                echartList = [];
                date = [];
                color = "#FF1926";
                for (var i = 0; i < result.echartList.length; i++) {
                    if (result.echartList[i].total != undefined) {
                        echartList.push(result.echartList[i].total);
                    }
                }
                for (var i = 0; i < result.echartList.length; i++) {
                    if (result.echartList[i].hourDate != undefined) {
                        date.push(result.echartList[i].hourDate);
                    }
                }
                var option=setOptionParamBar(result);
                chartToTotal.setOption(option);
            } else {
                chartToTotal.clear();
                document.getElementById('chartToTotalHour').style.display='none';
            }
        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败!");
            chartToTotal.hideLoading();
        }
    });
};

function chartToTotalOfSexAndAgeFunction(type) {
    var equipmentCode = $("#keyword").val();
    if (equipmentCode.length==0){
        return;
    }
    var param3 = $("#startDate-d").val();
    var param4 = $("#overDate-d").val();
    if(type=='1'){
        var chartToTotalOfSexAndAge = chartToTotal3;
        document.getElementById('chartToTotalOfSex').style.display='';
    }
    if(type=='2'){
        var chartToTotalOfSexAndAge = chartToTotal4;
        document.getElementById('chartToTotalOfAge').style.display='';
    }
    $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: path + "postion/chartToSexAndAge",    //请求发送到getTig处
        data: {param1: 'customer_flow_total',
            param2:type,
            param3:param3,
            param4:param4,
            equipmentCode:equipmentCode},
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            //请求成功时执行该函数内容，result即为服务器返回的json对象
            if (result.ageList.length != undefined) {
                ageList = [];
                data = [];
                var obj= result.ageList[0];
                for(var key in obj){
                    ageList.push({"value":obj[key],"name":key});
                    data.push(key);
                }
                chartToTotalOfSexAndAge.clear();
                var option=setOptionParamOnePie(result);
                chartToTotalOfSexAndAge.setOption(option);
            } else {
                chartToTotalOfSexAndAge.clear();
                if(type=='1'){
                    document.getElementById('chartToTotalOfSex').style.display='none';
                }
                if(type=='2'){
                    document.getElementById('chartToTotalOfAge').style.display='none';
                }
            }
        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败!");
            chartToTotalOfSexAndAge.hideLoading();
        }
    });
};

/*嵌套饼状图逻辑
function chartToTotalOfSexAndAgeFunction() {
    var equipmentCode = $("#keyword").val();
    if (equipmentCode.length==0){
        return;
    }
    var param3 = $("#startDate-d").val();
    var param4 = $("#overDate-d").val();
    $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: path + "postion/chartToSexAndAge",    //请求发送到getTig处
        data: {param1: 'customer_flow_total_copy',
            param3:param3,
            param4:param4,
            equipmentCode:equipmentCode},
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            //请求成功时执行该函数内容，result即为服务器返回的json对象
            if (result.sexList.length != undefined) {
                sexList = [];
                ageList = [];
                testList = [];
                data = [];
                /!*sexList = JSON.stringify(result.sexList[0]);
                ageList = JSON.stringify(result.ageList[0]);*!/
                var objsex = result.sexList[0];
                var objage = result.ageList[0];
                for(var key in objsex){
                    sexList.push({"value":objsex[key],"name":key});
                }
                for(var key in objage){
                    ageList.push({"value":objage[key],"name":key});
                    data.push(key);
                }
                chartToTotalOfSexAndAge.clear();
                var option=setOptionParamPie(result);
                chartToTotalOfSexAndAge.setOption(option);
            } else {
                chartToTotalOfSexAndAge.clear();
                option.series[0].data = "暂无数据"
                chartToTotalOfSexAndAge.setOption(option);
            }
        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败!");
            chartToTotal.hideLoading();
        }
    });
};*/

function chartToTotalAgeFunction(type) {
    var equipmentCode = $("#keyword").val();
    if (equipmentCode.length==0){
        return;
    }
    var param3 = $("#startDate-d").val();
    var param4 = $("#overDate-d").val();
    if(type=='1'){
        var chartToTotalOneAge = chartToTotalAge1;
        document.getElementById('chartToTotalEarlyYouth').style.display='';
    }
    if(type=='2'){
        var chartToTotalOneAge = chartToTotalAge2;
        document.getElementById('chartToTotalYouth').style.display='';
    }
    if(type=='3'){
        var chartToTotalOneAge = chartToTotalAge3;
        document.getElementById('chartToTotalAdult').style.display='';
    }
    if(type=='4'){
        var chartToTotalOneAge = chartToTotalAge4;
        document.getElementById('chartToTotalMeddleAge').style.display='';
    }
    if(type=='5'){
        var chartToTotalOneAge = chartToTotalAge5;
        document.getElementById('chartToTotalOldAge').style.display='';
    }
    $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: path + "postion/chartToOneAge",    //请求发送到getTig处
        data: {param1: 'customer_flow_total',
            param2:type,
            param3:param3,
            param4:param4,
            equipmentCode:equipmentCode},
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            //请求成功时执行该函数内容，result即为服务器返回的json对象
            if (result.ageList.length != undefined) {
                ageList = [];
                data = [];
                var objage = result.ageList[0];
                for(var key in objage){
                    ageList.push({"value":objage[key],"name":key});
                    data.push(key);
                }
                chartToTotalOneAge.clear();
                var option=setOptionParamOnePie(result);
                chartToTotalOneAge.setOption(option);
            } else {
                chartToTotalOneAge.clear();
                if(type=='1'){
                    document.getElementById('chartToTotalEarlyYouth').style.display='none';
                }
                if(type=='2'){
                    document.getElementById('chartToTotalYouth').style.display='none';
                }
                if(type=='3'){
                    document.getElementById('chartToTotalAdult').style.display='none';
                }
                if(type=='4'){
                    document.getElementById('chartToTotalMeddleAge').style.display='none';
                }
                if(type=='5'){
                    document.getElementById('chartToTotalOldAge').style.display='none';
                }
            }
        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败!");
            chartToTotal.hideLoading();
        }
    });
};

function setOptionParamBar(result) {
    if (result.echartList.length != undefined) {
        var option = {
            /*title: {
                left: '5%',
                textStyle: {
                    fontSize: 25,
                    color: '#333'          // 主标题文字颜色
                },
                text: ''
            }*/
            backgroundColor:'#20152b',
            title: {
                textStyle: {
                    fontSize: 45,
                    color: '#fff'          // 主标题文字颜色
                },
                text: result.echartName,
                x: 'center'
            },
            /*tooltip: {},
            legend: {
                data: [result.echartName]
            },*/
            xAxis: {
                data: date,
                axisLabel: {
                    show: true,
                    textStyle: {
                        color: '#fff',
                        fontSize: 30
                    }
                }
            },
            dataZoom: [{
                type: 'slider',
                show: true,
                xAxisIndex: [0],
                left: '9%',
                bottom: -5,
                start: 0,
                end: 100 //初始化滚动条
            }],
            yAxis: [
                {
                    axisLabel: {
                        formatter: '{value}',
                        textStyle: {
                            color: '#fff',
                            fontSize: 30
                        }
                    }
                }
            ],
            toolbox: {
                show: true,
                orient: 'horizontal',
                showTitle: true,
                feature: {
                    magicType: {
                        type: ['line']
                    },
                    saveAsImage: {
                        type: 'png',
                        show: true,
                        title: '保存为图片',
                    },
                    restore: {show: true}
                }
            },
            series: [
                {
                    name: result.echartName,
                    type: 'bar',
                    data: echartList,
                    barWidth: '60%',
                    //柱子颜色
                    color: color,
                    itemStyle:{
                        normal:{
                            label:{
                                show:true,
                                position:'top',
                                textStyle:{
                                    color:'#fff',
                                    fontSize:30
                                }
                            }
                        }
                    }
                }
            ]
        };
        return option;
    } else {

    }
};
//嵌套饼状图，保留不要删除
/*
function setOptionParamPie(result) {
    if (result.sexList.length != undefined) {
        option = {
            title : {
                text: result.name,
                x:'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b}: {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                x: 'left',
                data:data
            },
            toolbox: {
                show: true,
                orient: 'horizontal',
                showTitle: true,
                feature: {
                    magicType: {
                        type: ['line']
                    },
                    saveAsImage: {
                        type: 'png',
                        show: true,
                        title: '保存为图片',
                    },
                    restore: {show: true}
                }
            },
            series: [
                {
                    name:result.sexName,
                    type:'pie',
                    selectedMode: 'single',
                    radius: [0, '30%'],

                    label: {
                        normal: {
                            position: 'inner',
                            formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
                            backgroundColor: '#eee',
                            borderColor: '#aaa',
                            borderWidth: 1,
                            borderRadius: 4,
                            // shadowBlur:3,
                            // shadowOffsetX: 2,
                            // shadowOffsetY: 2,
                            // shadowColor: '#999',
                            // padding: [0, 7],
                            rich: {
                                a: {
                                    color: '#999',
                                    lineHeight: 22,
                                    align: 'center'
                                },
                                // abg: {
                                //     backgroundColor: '#333',
                                //     width: '100%',
                                //     align: 'right',
                                //     height: 22,
                                //     borderRadius: [4, 4, 0, 0]
                                // },
                                hr: {
                                    borderColor: '#aaa',
                                    width: '100%',
                                    borderWidth: 0.5,
                                    height: 0
                                },
                                b: {
                                    fontSize: 10,
                                    lineHeight: 33
                                },
                                per: {
                                    color: '#eee',
                                    backgroundColor: '#334455',
                                    padding: [2, 4],
                                    borderRadius: 2
                                }
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:sexList
                },
                {
                    name:result.ageName,
                    type:'pie',
                    radius: ['40%', '55%'],
                    label: {
                        normal: {
                            formatter: '{a|{a}}{abg|}\n{hr|}\n  {b|{b}：}{c}  {per|{d}%}  ',
                            backgroundColor: '#eee',
                            borderColor: '#aaa',
                            borderWidth: 1,
                            borderRadius: 4,
                            // shadowBlur:3,
                            // shadowOffsetX: 2,
                            // shadowOffsetY: 2,
                            // shadowColor: '#999',
                            // padding: [0, 7],
                            rich: {
                                a: {
                                    color: '#999',
                                    lineHeight: 22,
                                    align: 'center'
                                },
                                // abg: {
                                //     backgroundColor: '#333',
                                //     width: '100%',
                                //     align: 'right',
                                //     height: 22,
                                //     borderRadius: [4, 4, 0, 0]
                                // },
                                hr: {
                                    borderColor: '#aaa',
                                    width: '100%',
                                    borderWidth: 0.5,
                                    height: 0
                                },
                                b: {
                                    fontSize: 16,
                                    lineHeight: 33
                                },
                                per: {
                                    color: '#eee',
                                    backgroundColor: '#334455',
                                    padding: [2, 4],
                                    borderRadius: 2
                                }
                            }
                        }
                    },
                    data:ageList
                }
            ]
        };
        return option;
    } else {
        chartToTotalOfManWoman.clear();
        option.series[0].data = "暂无数据"
        chartToTotalOfManWoman.setOption(option);
    }
};
*/

function setOptionParamOnePie(result) {
    if (result.ageList.length != undefined) {
        option = {
            backgroundColor:'#20152b',
            title: {
                textStyle: {
                    fontSize: 25,
                    color: '#fff'          // 主标题文字颜色
                },
                text: result.name,
                x: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            color:['#ff1926', '#1a6cff'],
            legend: {
                orient: 'vertical',
                left: 'left',
                data: data,
                textStyle: {
                    color: '#fff'          // 主标题文字颜色
                },
            },
            toolbox: {
                show: true,
                orient: 'horizontal',
                showTitle: true,
                feature: {
                    magicType: {
                        type: ['line']
                    },
                    saveAsImage: {
                        type: 'png',
                        show: true,
                        title: '保存为图片',
                    },
                    restore: {show: true}
                }
            },
            series: [
                {
                    name:'',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: ageList,
                    label:{            //饼图图形上的文本标签
                        normal:{
                            show:true,
                            position:'inner', //标签的位置
                            textStyle : {
                                fontWeight : 300 ,
                                fontSize : 16    //文字的字体大小
                            },
                            formatter:'{d}%'
                        }
                    },
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        return option;
    }
};
